/*

Copyright (c) 2021 唐佐林
WeChat : delphi_tang
EMail: delphi_tang@dt4sw.com

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

#include "dtpython.h"
#include "py_context.h"
#include "tx_context.h"
#include "cmsis_os2.h"
#include "app_utils.h"
#include "wifi_connect.h"
#include "utils_file.h"
#include "ipc_server.h"
#include "ipc_message.h"
#include "ipc_msg_const.h"

#include <stdio.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>

#define MAIN "main.py"

static void PrintToRepl(const char* str, size_t len)
{
    Message* msg = Message_New(IPC_TYPE_MSG, IPC_MSG_OUTPUT, 0, 0, str, len);

    if( msg )
    {
        Server_Send(msg);
    }

    free(msg);
}

static void RunAppMode(void)
{
    size_t size = 0;

    if( (UtilsFileStat(MAIN, &size) == 0) && (size > 0) )
    {
        DTPython_Init();
        DTPython_SetOutputHook(NULL);
        DTPython_RunFile(MAIN);
        DTPython_Deinit();
    }
    else
    {
        char buf[64] = {0};
    
        sprintf(buf, "Can NOT find \'%s\' to run.", MAIN);

        LastError(buf);
    }
}

static void SendAck(int ack, int r)
{
    Message* msg = Message_New(IPC_TYPE_CMD, ack, r, 0, 0, 0);

    if( msg )
    {
        Server_Send(msg);
    }

    free(msg);
}

static void CodeHandler(Message* msg)
{
    DTPython_RunCode((char*)msg->payload);

    SendAck(IPC_CMD_CODE_ACK, 0);
}

static void RunHandler(Message* msg)
{
    DTPython_RunFile((char*)msg->payload);

    SendAck(IPC_CMD_RUN_ACK, 0);
}

static void FileHandler(Message* msg)
{
    static int fd = -1;

    if( msg->index == 0 )
    {
        fd = UtilsFileOpen((char*)msg->payload, O_CREAT_FS | O_TRUNC_FS | O_WRONLY_FS, 0);
        
        if( fd == -1 )
        {
            SendAck(IPC_CMD_FILE_ACK, fd);
        }
    }
    else if( fd != -1)
    {
        int r = UtilsFileWrite(fd, (char*)msg->payload, msg->length);
        
        if( r != -1 )
        {
            if( msg->index == msg->total )
            {
                UtilsFileClose(fd);

                fd = -1;

                SendAck(IPC_CMD_FILE_ACK, 0);
            }
        }
        else
        {
            UtilsFileClose(fd);

            fd = -1;

            SendAck(IPC_CMD_FILE_ACK, r);
        }
    }
}

static void MsgHandler(Message* msg)
{
    if( msg->type == IPC_TYPE_CMD )
    {
        switch(msg->cmd)
        {
            case IPC_CMD_CODE:
                CodeHandler(msg);
                break;
            case IPC_CMD_RUN:
                RunHandler(msg);
                break;
            case IPC_CMD_FILE:
                FileHandler(msg);
                break;
            default:
                break;
        }
    }
}

static void RunReplMode(void)
{
    char* id = NULL;
    char* pwd = NULL;
    int err = GetWifiInfo(&id, &pwd);

    err = !err ? Wifi_Init() : -1;
    err = !err ? Wifi_Connect(id, pwd) : -1;
    err = !err ? Wifi_Start() : -1;

    if( err )
    {
        LastError("Can NOT connect to Wifi.");
        return;
    }

    err = !err ? Server_Init() : -1;
    err = !err ? Server_Start() : -1;

    if( err )
    {
        LastError("Can NOT start Python daemon.");
        return;
    }

    if( !err )
    {
        TX_Context_Entry();
        
        DTPython_Init();
        DTPython_SetModeRepl(1);
        DTPython_SetOutputHook(PrintToRepl);

        while( true )
        {
            Message* msg = NULL;

            Server_Accept();

            msg = Server_Recv();

            if( msg )
            {
                MsgHandler(msg);
            }

            free(msg);
        }

        DTPython_Deinit();
    }
}

static void* Py_Context_Task(const char* arg)
{
    char* mode = NULL;

    osDelay(100);

    mode = GetMode();

    if( mode && (strcmp(mode, "app") == 0) )
    {
        RunAppMode();
    }
    else
    {
        RunReplMode();
    }

    return (void*)arg;
}

void Py_Context_Entry(void)
{
    osThreadAttr_t attr = {0};

    attr.name = "Python Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 20;
    attr.priority = osPriorityNormal;

    if (osThreadNew((osThreadFunc_t)Py_Context_Task, NULL, &attr) == NULL)
    {
        printf("[dt4sw] Falied to create Python task!");
    }
}